﻿using System;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using HandyControl.Controls;
using Haidou.Wpf.Util;
using Haidou.Wpf.Native.Structs;

namespace Haidou.Wpf.UI.Windows.Composer
{
    /// <summary>
    /// FloatingBall.xaml 的交互逻辑
    /// </summary>
    public partial class FloatingBall : System.Windows.Window
	{


		[DllImport("user32.dll", EntryPoint = "GetWindowLong")]
		private static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex);

		[DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")]
		private static extern IntPtr GetWindowLong64(IntPtr hWnd, int nIndex);

		[DllImport("user32.dll", EntryPoint = "SetWindowLong")]
		private static extern IntPtr SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);

		[DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")]
		private static extern IntPtr SetWindowLong64(IntPtr hWnd, int nIndex, IntPtr dwNewLong);

		public FloatingBall()
        {
			//移动到左中位置
			SizeChanged += (o, e) =>
			{
				Rect r = SystemParameters.WorkArea;
				Left = r.Right - ActualWidth - 100;
				Top = r.Bottom - ActualHeight - 600;
			};



			InitializeComponent();

			try
			{


				PreviewLostKeyboardFocus += Window_PreviewLostKeyboardFocus;

				Keyboard.ClearFocus();
				SourceInitialized += OnSourceInitialized;
			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow FloatingWindow", ex.Message);
			}

        }
		private void OnSourceInitialized(object sender, EventArgs e)
		{
			try
			{


				IntPtr handle = new WindowInteropHelper(this).Handle;
				IntPtr exstyle = GetWindowLong(handle, GWL_EXSTYLE);
				SetWindowLong(handle, GWL_EXSTYLE, new IntPtr(exstyle.ToInt32() | WS_EX_NOACTIVATE));
			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow OnSourceInitialized", ex.Message);
			}

		}



		#region Native Methods

		private const int WS_EX_NOACTIVATE = 0x08000000;
		private const int GWL_EXSTYLE = -20;

		public static IntPtr GetWindowLong(IntPtr hWnd, int nIndex)
		{
			try
			{



				return Environment.Is64BitProcess
					? GetWindowLong64(hWnd, nIndex)
					: GetWindowLong32(hWnd, nIndex);
			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow GetWindowLong", ex.Message);
				return IntPtr.Zero;
			}
		}

		public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
		{

			try
			{


				return Environment.Is64BitProcess
					? SetWindowLong64(hWnd, nIndex, dwNewLong)
					: SetWindowLong32(hWnd, nIndex, dwNewLong);

			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow SetWindowLong", ex.Message);
				return IntPtr.Zero;

			}
		}



		#endregion


		private static KeyBordHook k_hook = new();

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			try
			{



				//App_Startup.DisplayAppFloatingWindow();
				Keyboard.ClearFocus();

				PointW p = new()
				{
					X = (int)Left,
					Y = (int)Top
				};
				//Global.FloatingMenuPointW = p;



				k_hook.KeyDownEvent += new System.Windows.Forms.KeyEventHandler(hook_KeyDown);//钩住键按下 
				k_hook.KeyUpEvent += K_hook_KeyUpEvent;
				k_hook.Start();//安装键盘钩子
			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow Window_Loaded", ex.Message);
			}


		}
		public static bool Status = false;


		private void hook_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			try
			{



				Debug.WriteLine("监听到按下了");
				Debug.WriteLine(e.KeyCode.ToString());


				////判断按下的键
				//if (e.KeyCode.ToString() == UserSettings.All.ScreenshotShortcut.ToString() && (int)Control.ModifierKeys == (int)UserSettings.All.ScreenshotModifiers)
				//{


				//}
				//else if (e.KeyCode.ToString() == UserSettings.All.CustomKeySettingsShortcut.ToString() && (int)Control.ModifierKeys == (int)UserSettings.All.CustomKeySettingsModifiers)
				//{
				//	if (!Status)
				//	{
				//		Status = false;
				//		MKeyPressProcessing();

				//	}


				//}
			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow hook_KeyDown", ex.Message);
			}

		}

		private void K_hook_KeyUpEvent(object? sender, System.Windows.Forms.KeyEventArgs e)
		{

			try
			{



				//Debug.WriteLine("监听到松开了");
				//Status = false;

				////判断按下的键
				//if (e.KeyCode.ToString() == UserSettings.All.ScreenshotShortcut.ToString() && (int)Control.ModifierKeys == (int)UserSettings.All.ScreenshotModifiers)
				//{


				//}
				//else if (e.KeyCode.ToString() == UserSettings.All.CustomKeySettingsShortcut.ToString() && (int)Control.ModifierKeys == (int)UserSettings.All.CustomKeySettingsModifiers)
				//{
				//	MkeyLooseningTreatment();

				//}
			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow K_hook_KeyUpEvent", ex.Message);
			}

		}







		private void Window_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
		{
			System.Windows.Window window = (System.Windows.Window)sender;
			window.Topmost = true;
		}


		/// <summary>
		/// 语音按钮
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Translate_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			try
			{


				//if (Global.MicrophoneAvailabilityStatus == true)
				//{
				//	Debug.WriteLine("按下");
				//	Keyboard.ClearFocus();

				//	Moser_HID_Startup.MouseRecordingStart();
				//}
				//else
				//{
				//	Growl.ClearGlobal();
				//	Growl.ErrorGlobal("没有可用的麦克风输入源噢！！！");
				//}

			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow Translate_PreviewMouseDown", ex.Message);
			}

		}

		/// <summary>
		/// 语音按钮
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Translate_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			try
			{


				//if (Global.MicrophoneAvailabilityStatus == true)
				//{
				//	Debug.WriteLine("松开");
				//	Keyboard.ClearFocus();

				//	Moser_HID_Startup.MouseRecordingStop();
				//}
				//else
				//{
				//	//Growl.ErrorGlobal("没有可用的麦克风输入源噢！！！"); //松开不显示了
				//}
			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow Translate_PreviewMouseUp", ex.Message);
			}

		}

		private void menu_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			DragMove();
		}



		private void menu_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
		{
			try
			{


				//App.MainViewModel.Open.Execute(15);
				////Debug.WriteLine("Open");
				//Global.Doyouwanttoleavethecontrol = false;
			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow menu_MouseEnter", ex.Message);
			}
		}

		private async void menu_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
		{

			try
			{


				//Global.Doyouwanttoleavethecontrol = true;

				//await Task.Delay(200);

				////Debug.WriteLine(Global.Doyouwanttoleavethecontrol);

				//if (Global.Doyouwanttoleavethecontrol)
				//{

				//	App.MainViewModel.Open.Execute(16);
				//	//Debug.WriteLine("Hide");
				//}

			}
			catch (Exception ex)
			{

				//LogWriter.Log("FloatingWindow menu_MouseLeave", ex.Message);
			}

			//Debug.WriteLine("Hide");

		}

		/// <summary>
		///  
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void MBtn_PreviewMouseDown(object sender, MouseButtonEventArgs e)
		{
			MKeyPressProcessing();
		}

		/// <summary>
		/// 松开
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>

		private void MBtn_PreviewMouseUp(object sender, MouseButtonEventArgs e)
		{
			MkeyLooseningTreatment();
		}




		/// <summary>
		/// M键按下处理
		/// </summary>
		public static void MKeyPressProcessing()
		{


			//if (Moser_HID_Startup.Returnornot())
			//{
			//	return;
			//}

			//LogWriter.OperationLog("MKeyPressProcessing：-----  鼠标M键按下  -----");
			//Debug.WriteLine("按下M");

			/////根据设定的模式执行相应操作
			//M_keyAllocationExecution.execute();//开始执行M


		}




		/// <summary>
		/// M键松开处理
		/// </summary>
		public static void MkeyLooseningTreatment()
		{
			//Global.MouseM_Dstareceived = false;//设置松开了
			//Arguments.MouseM_Dstareceived = false;
			//LogWriter.OperationLog("MkeyLooseningTreatment：-----  鼠标M键松开  -----");
			//Debug.WriteLine("松开M");
			//if (Global.MouseMKey == MouseMKey.Phonetictyping || Global.MouseMKey == MouseMKey.Translationtyping)
			//{
			//	Moser_HID_Startup.MouseRecordingStop();
			//	LogWriter.OperationLog("MkeyLooseningTreatment：-----  鼠标M键松开 停止了录音  -----");
			//	//StartTheDefaultBrowser.StartBaidu();
			//}
			//else if (Global.MouseMKey == MouseMKey.voicesearch)
			//{
			//	Moser_HID_Startup.MouseRecordingStop();
			//	LogWriter.OperationLog("MkeyLooseningTreatment：-----  鼠标M键松开 停止了录音  -----");
			//	//这里会涉及到默认浏览器，应该使用应用的默认搜索引擎  只是修改访问地址，不修改浏览器....
			//}

		}

		private void Window_Closed(object sender, EventArgs e)
		{
			//try
			//{


			//	k_hook.Stop();
			//}
			//catch (Exception ex)
			//{

			//	LogWriter.Log("FloatingWindow Window_Closed", ex.Message);
			//}
		}




	}
}
